<template>
  <view class="order-list-container">
    <u-navbar title="可回收订单" :is-back="true" title-color="black" :border-bottom="false" :custom-back="customBack"
              :background="background"/>
    <!-- 订单列表 -->
    <scroll-view
        scroll-y
        class="orders-scroll"
        @scroll="handleScroll"
        enable-flex
        scroll-with-animation
        enable-passive
    >
      <view v-if="filteredOrders.length === 0" class="no-orders">暂无订单</view>
      <view
          v-for="(order, index) in filteredOrders"
          :key="index"
          class="order-card"

      >
        <view class="order-details">
          <view class="order-info column">
            <view class="order-item row">
              <view class="order-label">订单编号:</view>
              <view class="flex-1 row-between">
                <text class="order-value">{{ order?.order_number }}</text>
                <view class="copy-icon " @click="copyText(order.order_number)">复制</view>
              </view>
            </view>
            <view class="order-item">
              <text class="order-label">联系方式:</text>
              <text>{{ order.contact_number }}</text>
            </view>
            <!--            <view class="order-item">-->
            <!--              <text class="order-label">回收类型:</text>-->
            <!--              <text>{{ order.recycle_type === '1' ? '衣服' : '鞋帽' }}</text>-->
            <!--            </view>-->
            <view class="order-item">
              <text class="order-label">预估重量:</text>
              <text>{{ order.estimated_weight }}</text>
            </view>
            <view class="order-item" v-if="order.order_status === '2'">
              <text class="order-label">实际重量:</text>
              <text>{{ order.actual_weight }}kg</text>
            </view>
            <view class="order-item">
              <text class="order-label">预约时间:</text>
              <text>{{ order.pickup_time }}</text>
            </view>
            <view class="order-item" v-if="order.order_status === '2'">
              <text class="order-label">取件时间:</text>
              <text>{{ order.pick_up_time }}</text>
            </view>
            <view class="order-item">
              <text class="order-label">取件地址:</text>
              <text>{{ order.pickup_address }}</text>
            </view>

            <view class="order-item">
              <text class="order-label">订单状态:</text>
              <text>{{
                  order.order_status === 0 ? '等待上门' : order.order_status === 1 ? '回收中' : order.order_status === 2 ? '已完成' : order.order_status === 3 ? '已取消' : ''
                }}
              </text>
            </view>
            <view class="order-item">
              <text class="order-label">下单时间:</text>
              <text>{{ timeFormat(order.order_time, 'yy-mm-dd hh:MM:ss') }}</text>
            </view>
          </view>
          <view class="payment">
            <u-button type="info" shape="circle" size="medium" class="mr20" @click="goToCustomerService">咨询客服
            </u-button>
            <u-button type="primary" shape="circle" size="medium" @click="acceptOrder(order)"
                      v-if="order.order_status === 0">接单
            </u-button>
            <u-button type="success" shape="circle" size="medium"
                      v-if="order.order_status === 1">已被接单
            </u-button>
          </view>
        </view>
      </view>
      <!-- 在 scroll-view 底部添加 -->
      <view v-if="isLoading" class="loading-tips">加载中...</view>
      <view v-if="!hasMoreData && filteredOrders.length > 0" class="no-more"
      >没有更多订单了
      </view>
    </scroll-view>
    <tabbar/>
  </view>
  <u-popup v-model="showContactPopup" mode="center" border-radius="20" width="80%" :closeable="true">
    <view class="popup-content">
      <view class="popup-title">确认接单</view>
      <view class="order-number">订单号：{{ currentOrder?.order_number }}</view>
      <view class="popup-buttons">
        <u-button
            type="info"
            shape="circle"
            size="medium"
            @click="showContactPopup = false"
            class="cancel-btn"
        >
          取消
        </u-button>
        <u-button
            type="primary"
            shape="circle"
            size="medium"
            @click="confirmAcceptOrder"
            class="confirm-btn"
        >
          确认接单
        </u-button>
      </view>
    </view>
  </u-popup>
</template>

<script lang="ts" setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {onLoad, onShow, onReady} from '@dcloudio/uni-app'
import {apiListsOtherOrder, apiAcceptOrder} from "@/api/order";
import {timeFormat} from "@/utils/util";
import UButton from "@/uni_modules/vk-uview-ui/components/u-button/u-button.vue";

const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = 10 // 每页数据量
const hasMoreData = ref(true) // 是否还有更多数据
const isLoading = ref(false) // 防止重复加载
const showContactPopup = ref(false)

const currentOrder = ref(null)

const background = {
  position: 'fixed', // 固定定位（相对于视口）
  top: '0',         // 使用字符串并添加单位
  left: '0',
  right: '0',
  zIndex: 999       // 确保层级足够高
}
// 当前选中的 tab
const activeTab = ref('')
// 订单数据
const orders = ref([])

// 新增：刷新订单列表
const refreshOrders = async () => {
  currentPage.value = 1
  hasMoreData.value = true
  await getOrders()
}
const getOrders = async (isLoadMore = false) => {
  if (isLoading.value || !hasMoreData.value) return

  isLoading.value = true
  try {
    const data = await apiListsOtherOrder({

      keyword: searchKeyword.value,
      page_no: isLoadMore ? currentPage.value + 1 : 1, // 分页逻辑
      page_size: pageSize
    })
    const newOrders = data.data || []

    if (isLoadMore) {
      orders.value = [...orders.value, ...newOrders] // 追加数据
    } else {
      orders.value = newOrders // 替换数据
    }

    // 更新分页状态
    currentPage.value = isLoadMore ? currentPage.value + 1 : 1
    hasMoreData.value = newOrders.length >= pageSize // 判断是否还有数据
  } catch (error) {
    console.error('获取订单数据失败:', error)
  } finally {
    isLoading.value = false
  }
}
onMounted(() => {
  getOrders()
})

const goToCustomerService = () => {
  uni.navigateTo({
    url: '/pages/customer_service/customer_service'
  })
}
const filteredOrders = computed(() => {
  if (!searchKeyword.value) return orders.value
  const keyword = searchKeyword.value.toLowerCase()
  return orders.value.filter(
      (order) => order.id.includes(keyword) || order.name?.toLowerCase().includes(keyword)
  )
})
const goToOrderDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/order/order_detail?id=${id}`
  })
}


const copyText = (text: string) => {
  if (!text) {
    uni.showToast({title: '订单号为空', icon: 'none'});
    return;
  }

  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({title: '复制成功', icon: 'success'});
    },
    fail: () => {
      uni.showToast({title: '复制失败，请手动复制', icon: 'none'});
    }
  });
};

const customBack = () => {
  uni.switchTab({
    url: '/pages/user/user' // 确保路径正确
  })
}
const handleScroll = (e: any) => {
  const {scrollTop, scrollHeight} = e.detail
  const systemInfo = uni.getSystemInfoSync()
  // 计算可视区域高度（窗口高度 - 导航栏高度 - 搜索框高度 - 其他固定元素高度）
  const clientHeight = systemInfo.windowHeight - 80 // 80rpx 是导航栏+搜索框估算高度

  // 增加防抖和加载锁
  if (isLoading.value) return

  // 判断是否滚动到底部（距离底部 < 10px）
  const isBottom = scrollHeight - scrollTop - clientHeight < 10
  console.log(`滚动位置: ${scrollTop}, 内容高度: ${scrollHeight}, 可视高度: ${clientHeight}`)

  console.log('滚动到底部:', isBottom)
  if (isBottom) {
    getOrders(true) // 触发加载更多
  }
}

const acceptOrder = async (order) => {
  // // 弹出输入框让用户填写联系方式
  // uni.showModal({
  //   title: "确认接单",
  //   content: `订单号：${order.order_number}\n请确认您的联系方式：`,
  //   editable: true,
  //   placeholderText: "请输入您的联系方式",
  //   confirmColor: "#236af6", // 确认按钮颜色
  //   cancelColor: "#999999",  // 取消按钮颜色
  //   success: async (res) => {
  //     if (res.confirm) {
  //       const contactInfo = res.content;
  //
  //       // 验证联系方式
  //       if (!contactInfo || contactInfo.trim() === '') {
  //         uni.showToast({title: "请输入联系方式", icon: "none"});
  //         return;
  //       }
  //
  //       uni.showLoading({title: "接单中..."});
  //       try {
  //         // 调用接单接口，传递订单ID和联系方式
  //         const success = await apiAcceptOrder({
  //           id: order.id,
  //           contact_info: contactInfo // 传递联系方式
  //         });
  //
  //         if (success) {
  //           uni.showToast({title: "接单成功", icon: "success"});
  //           await refreshOrders();
  //         } else {
  //           uni.showToast({title: "接单失败", icon: "none"});
  //         }
  //       } catch (error) {
  //         uni.showToast({title: "接单失败，请重试", icon: "none"});
  //       } finally {
  //         uni.hideLoading();
  //       }
  //     }
  //   },
  // });
  currentOrder.value = order
  showContactPopup.value = true
}

// 新增确认接单方法
const confirmAcceptOrder = async () => {

  showContactPopup.value = false
  uni.showLoading({title: "接单中..."})

  try {
    // 调用接单接口，传递订单ID和联系方式
    const success = await apiAcceptOrder({
      id: currentOrder.value.id
    })

    if (success) {
      uni.showToast({title: "接单成功", icon: "success"})

      await refreshOrders()
      // 接单成功后跳转到订单详情页
      uni.navigateTo({
        url: `/pages/order/order`
      })
    } else {
      uni.showToast({title: "接单失败", icon: "none"})
    }
  } catch (error) {
    uni.showToast({title: "接单失败，请重试", icon: "none"})
  } finally {
    uni.hideLoading()
  }
}


onShow(() => {
  const params = uni.getStorageSync('orderPageParams');
  if (params.type != undefined) {
    activeTab.value = String(params.type)
  }
  refreshOrders();
})

</script>

<style lang="scss">
.order-list-container {
  background-image: linear-gradient(to bottom, #236af6, #ffffff); /* 添加渐变 */
  background-color: #ffffff;
  background-repeat: no-repeat;
  background-size: 100% 20%;

}

.orders-scroll {
  height: calc(100vh - 200rpx); // 增加底部预留高度
  //border: 1rpx solid red; // 添加边框辅助调试
  overflow: hidden; // 避免内容溢出
}

.no-orders {
  text-align: center;
  margin-top: 100rpx;
  color: #999;
}

.order-card {
  display: flex;
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  flex: 1;
  border-radius: 16rpx;
}

.order-image {
  width: 240rpx;
  height: 240rpx;
  margin-right: 20rpx;
  border-radius: 8rpx;
}

.order-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.order-name {
  font-size: 32rpx;
  font-weight: bold;
}

.order-date,
.order-travelers {
  font-size: 26rpx;
  color: #666;
}

.time-slot {
  display: flex;
  font-size: 24rpx;
  flex-direction: column;
  background-color: #f8f8f8;
  color: #6e7681;
  border-radius: 8rpx;
  line-height: 1.5;
  padding: 15rpx;
  margin-bottom: 15rpx;
}

.payment {
  //background-color: #fff;
  display: flex;
  justify-content: flex-end;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  color: #f6a22d;
}

.order-status {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 28rpx;
  font-weight: bold;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}

.pay_btn {
  border-radius: 60rpx;
  background-color: #fef1e0;
  color: #f6a22d;
  width: 220rpx;
  margin: 0;
  border: none;
}

.status-pending {
  color: #ffffff;
  background-color: #ff4d4f;
}

.status-awaiting {
  color: #ffffff;
  background-color: #faad14;
}

.status-confirmed {
  color: #ffffff;
  background-color: #1890ff;
}

.status-progress {
  color: #ffffff;
  background-color: #13c2c2;
}

.status-review {
  color: #f6a22d;
  background-color: #fffbf6;
  border: 1rpx solid #fbdaab;
}

.status-completed {
  color: #ffffff;
  background-color: #f6a22d;
}

.status-refunded {
  color: #ffffff;
  background-color: #8c8c8c;
}

.order-type {
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  position: absolute;
  font-size: 24rpx;
  z-index: 999;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.loading-tips,
.no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
}

.order-item {
  padding: 10rpx 0
}

.order-label {
  font-weight: bold;
  margin-right: 50rpx;
}

.copy-icon {
  color: #236af6;
  justify-self: self-end;
  font-weight: bold;
}

.popup-content {
  padding: 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
  color: #333;
}

.order-number {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
  text-align: center;
}


.popup-buttons {
  margin-top: 40rpx;
  display: flex;
  justify-content: space-between;

  .cancel-btn {
    flex: 1;
    margin-right: 20rpx;
  }

}

</style>
